<?php

# Function for preventing SQL Injection
if (!function_exists("GetSQLValueString")) {
	function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") {

		$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
		$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : 
		mysql_escape_string($theValue);
		switch ($theType) {
			case "text":
			$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
			break;    
			case "long":
			case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL";
			break;
			case "double": $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
			break;
			case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
			break;
			case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
			break;
		}
		return $theValue;
	}

}

if (!function_exists("CheckLoggedIn")) {
	function CheckLoggedIn() {
		$checked_in = false;
		
		if (isset($_SESSION['username']) && !empty($_SESSION['username'])) {
			$checked_in = true;
		} 
		
		return $checked_in;
	}

}


if (!function_exists("LoginUser")) {
	function LoginUser($id = "",  $user="", $pw="") {
		
		if (CheckLoggedIn()) {
			return $_SESSION['id'];
		}
		
		
		require($_SERVER['DOCUMENT_ROOT'].'/database/db.php');
		
		$new_id = -1;
		
		if (isset($_COOKIE['id']) && $id == "") {
			$id = $_COOKIE['id'];
		}
		
		$where_clause = "";
		if ($id == "" && $user != "" && $pw != "") {
			$where_clause = "WHERE username = '$user' AND password = '$pw'";
		} else {
			$where_clause = $id == "" ? "WHERE id = -1" : "WHERE id = $id";
		}
		

		#lookup the user
		$qry = "SELECT id, username, first_name, last_name, is_dealer, is_seller FROM contacts $where_clause";
		mysql_select_db($db_name, $db);
		$rs = mysql_query($qry) or die(mysql_error()."<br />".$qry);
		$row = mysql_fetch_assoc($rs);
		if (mysql_num_rows($rs) > 0) {
			$new_id = $row['id'];
			$_SESSION['username'] = $row["username"];
			$_SESSION['dealer'] = $row["is_dealer"] == 1 ? true : false;
			$_SESSION['seller'] = $row["is_seller"] == 1 ? true : false;
			$_SESSION['full_name'] = $row['first_name']." ".$row['last_name'];
			$_SESSION['id'] = $row['id'];
		}
	
		return $new_id;
	}

}

if (!function_exists("LogoutUser")) {
	function LogoutUser() {
		$_SESSION['username'] = "";
		$_SESSION['dealer'] = "";
		$_SESSION['seller'] = "";
		$_SESSION['full_name'] = "";
		$_SESSION['id'] = "";
	}
}


if (!function_exists("CheckUserExists")) {
	function CheckUserExists($user="") {
		require($_SERVER['DOCUMENT_ROOT'].'/database/db.php');
		$qry = "SELECT id FROM contacts WHERE username = ".GetSQLValueString($user, "text");
		mysql_select_db($db_name, $db);
		$rs = mysql_query($qry) or die(mysql_error()."<br />".$qry);
		return (mysql_num_rows($rs) > 0);
	}
		
}
?>